package cc.rengu.redp.bizimpl.upmp.service.impl;

import cc.rengu.igas.bomp.facade.bean.TermInfoBean;
import cc.rengu.redp.bizimpl.enums.BizDataAuditStatusEnum;
import cc.rengu.redp.bizimpl.enums.BizDataStatusEnum;
import cc.rengu.redp.bizimpl.enums.BizOprEnum;
import cc.rengu.redp.bizimpl.upmp.common.BusinessContainer;
import cc.rengu.redp.bizimpl.upmp.dao.MerchantBaseInfoMapper;
import cc.rengu.redp.bizimpl.upmp.domain.*;
import cc.rengu.redp.bizimpl.upmp.service.*;
import cc.rengu.redp.bizimpl.upmp.vo.UpmpUserInfoVO;
import cc.rengu.redp.bizimpl.utils.CommonUtils;
import cc.rengu.redp.bizimpl.utils.DateUtils;
import cc.rengu.redp.bizimpl.utils.GZIPUtils;
import cc.rengu.redp.bizimpl.utils.RedpUpmpUtil;
import cc.rengu.redp.common.exception.RedpException;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.annotation.TableName;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.core.toolkit.ArrayUtils;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import io.swagger.annotations.ApiModel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import java.util.*;
import java.util.function.Function;
@Slf4j
@Service("merchantBaseInfoService")
public class MerchantBaseInfoServiceImpl implements MerchantBaseInfoService {

    @Autowired
    private MerchantBaseInfoMapper merchantBaseInfoMapper;
    @Autowired
private  MerchantBaseInfoService merchantBaseInfoService;
    @Autowired
    private  IBTermInfoService bTermInfoService;
    @Autowired
    private IUpmpOrganizationService upmpOrganizationService;
    @Autowired
    private IBizHisService bizHisService;
    @Autowired
    private IBizTmpService bizTmpService;
    @Autowired
    private IUpmpPrivilegeCheckService authPrivilegeCheckService;
    private final String oprMenuId = "30000006";
    private final String oprMenuName = "风险管理:商户限额管理:商户级限额管理";
    private final String webNextUrl = "bizimpl/upmp/quota/merchantLevelManager/MerchantLevelManagerInfo";
    /**
     * 获取商户级限额信息
     */
    @Override
    public Page<BTxnLimitCfg> getMerchantLevelList(HttpServletRequest request) throws RedpException {
        //获取列表数据
//        String instId = request.getParameter("instId");
//        List<BTxnLimitCfg> bTxnLimitCfgs = merchantBaseInfoMapper.getMerchantLevelList(instId);
//        return bTxnLimitCfgs;
        //Pageable pageable = PropertyFilter.buildPageableFromHttpRequest(request);
        //获取列表数据
        Page<BTxnLimitCfg> pageInfo = queryMcLevelList(request);
        return pageInfo;
    }

    /**
     * 查询
     */
    private PageImpl<BTxnLimitCfg> queryMcLevelList(HttpServletRequest request) throws RedpException {
        try {
            List<BTxnLimitCfg> cfgVosList = new ArrayList<>();
            String instId = "";
            UpmpUserInfoVO user = RedpUpmpUtil.getCurrentUser(request.getParameter("instId"));
            boolean flag = user.isAdmin();
//            if (flag) {
//                instId = request.getParameter("instId");
//            }
           /* if (!(flag) || StringUtils.isBlank(instId)) {
                instId = user.getInstId();
            }*/
            instId = request.getParameter("instId");
            if (StringUtils.isBlank(instId)) {
                throw new RedpException("多法人机构号为空");
            }
            String mchntNo = request.getParameter("mchntNo");
            String termNo = request.getParameter("termNo");
            //商户号为空  终端号不为空 终端号辅助查询商户号
            if (StringUtils.isNotBlank(termNo) && StringUtils.isBlank(mchntNo)) {
                BTermInfo termInfosByTmNo = bTermInfoService.getTermInfosByTmNo(instId, termNo);
                if (null != termInfosByTmNo && StringUtils.isNotBlank(termInfosByTmNo.getMchntNo())) {
                    mchntNo = termInfosByTmNo.getMchntNo();
                }
            }
            List<String> userOrgCodeList=null;
            if (!flag) {
                if (ArrayUtils.isNotEmpty(user.getUserOrgCodeArr())){
                    String userOrgCodes = GZIPUtils.uncompressToString(user.getUserOrgCodes());
                    String[] userOrgCodeArray = userOrgCodes.split(",");
                    userOrgCodeList = Arrays.asList(userOrgCodeArray);
                }
            }
            List resultListCount = merchantBaseInfoMapper.queryMcLevelList(instId, mchntNo, userOrgCodeList);
//            if (resultListCount.size() > 0) {
//                List resultList =resultListCount;
//                cfgVosList = mapTxnLimitCfgVoList(resultList);
//            }
            return new PageImpl<BTxnLimitCfg>(resultListCount);
        } catch (Exception e) {
            // TODO: handle exception
            log.error("交易出现异常，异常信息：" + e.getMessage());
            throw new RedpException("交易出现异常，异常信息：" + e.getMessage());
        }
    }
    /**
     * 通过商户号获取商户信息
     */
    public BTxnLimitCfg getMarchantInfoByMcNo(String instId, String mcNo) {
        return merchantBaseInfoMapper.getMarchantInfoByMcNo(instId, mcNo);
    }
    /**
     * 保存商户级限额信息
     */

    @Transactional(value = "transactionManager")
    public void saveMerchantQuotaInfo(BTxnLimitCfg txnCfginfo, HttpServletRequest request) throws RedpException {
        UpmpUserInfoVO user = RedpUpmpUtil.getCurrentUser(txnCfginfo.getInstId());
        UpmpOrganization org = upmpOrganizationService.getOrgByCode(user.getOrgCode(), user.getInstId());
        UpmpPrivilegeCheck privilegeCheckByPrivilegeCode = authPrivilegeCheckService.getPrivilegeCheckByPrivilegeCode(txnCfginfo.getInstId(), "merchantLevelManager:add");
        if (null == privilegeCheckByPrivilegeCode) {
            throw new RuntimeException("获取审核信息失败");
        }
        txnCfginfo.setNotDiffAcctId(CommonUtils.getUUID());
        txnCfginfo.setCreditId(CommonUtils.getUUID());
        txnCfginfo.setLoanId(CommonUtils.getUUID());
        txnCfginfo.setRefundNotDiffAcctId(CommonUtils.getUUID());
        txnCfginfo.setRefundLoanId(CommonUtils.getUUID());
        txnCfginfo.setRefundCreditId(CommonUtils.getUUID());
        txnCfginfo.setLimitInst(txnCfginfo.getMchntNo());
//        if(user.isAdmin()){
//            String instId = request.getParameter("instId");
//            UpmpOrganization headOrg = upmpOrganizationService.getHeadOrgByCode(instId);
//            String crtOrgId = headOrg == null ? user.getOrgCode() : headOrg.getOrgCode();
//            txnCfginfo.setInstId(instId);
//            txnCfginfo.setCrtOrgId(crtOrgId);
//        }else {
//            txnCfginfo.setInstId(user.getInstId());
//            txnCfginfo.setCrtOrgId(org.getOrgCode());
//        }
        txnCfginfo.setInstId(txnCfginfo.getInstId());
            txnCfginfo.setCrtOrgId(org.getOrgCode());
        boolean checked = BusinessContainer.YES.equals(privilegeCheckByPrivilegeCode.getChecked());
        if (checked) {
            //保存正式表

            txnCfginfo.setLimitType("11");

            txnCfginfo.setBizStatus(BizDataStatusEnum.STATUS_DRAFT.getType());
            txnCfginfo.setAuditStatus(BizDataAuditStatusEnum.AUDIT_STATUS_ADD_CHECKING.getType());
            txnCfginfo.setOprId(user.getOprId());
            txnCfginfo.setCreateTime(DateUtils.formatDate(new Date(), DateUtils.DEFAULT_TIME_FORMAT));
            txnCfginfo.setStatus("N");
            saveMerchantQutaInfo(txnCfginfo);

            //保存审核表
            saveBizTmp(txnCfginfo, BizOprEnum.OPR_ADD.getType());

        } else if (!checked) {
            //保存正式表

            txnCfginfo.setLimitType("11");
            txnCfginfo.setStatus("Y");
            txnCfginfo.setBizStatus(BizDataStatusEnum.STATUS_NORMAL.getType());
            txnCfginfo.setAuditStatus(BizDataAuditStatusEnum.AUDIT_STATUS_ADD_PASS.getType());
            txnCfginfo.setOprId(user.getOprId());
            txnCfginfo.setCreateTime(DateUtils.formatDate(new Date(), DateUtils.DEFAULT_TIME_FORMAT));

            saveMerchantQutaInfo(txnCfginfo);

            //保存历史表
            saveQuotaBizHis(txnCfginfo,null, BizOprEnum.OPR_ADD.getType());
        }
    }
    //保存临时表
    private void saveBizTmp(BTxnLimitCfg txnCfginfo, String oprType) throws RedpException {
        //主记录key
        String uuid = CommonUtils.getUUID();
        if (StringUtils.isNotBlank(oprType) && !(BizOprEnum.OPR_ADD.getType().equals(oprType))) {

            BizTmp tmp = bizTmpService.getById(txnCfginfo.getNotDiffAcctId());
            if(tmp!=null){
                String masterKey = tmp.getMasterKey();
                if (StringUtils.isNotBlank(masterKey)) {
                    uuid = masterKey;
                }
            }
        }
        UpmpUserInfoVO user = RedpUpmpUtil.getCurrentUser(txnCfginfo.getInstId());
        UpmpOrganization org = upmpOrganizationService.getOrgByCode(user.getOrgCode(), user.getInstId());
        List<BTxnLimitCfg> TxnDatalist = coverBizData(txnCfginfo);
        List<BizTmp> bizTmpList = new ArrayList<>();
        for (BTxnLimitCfg txnLimitCfg : TxnDatalist) {
            BizTmp tmp = coverBizTmp(txnLimitCfg, oprType, oprMenuId, oprMenuName, org.getOrgCode(), user.getInstId(), txnCfginfo.getBizStatus(), txnLimitCfg.getAuditStatus(), webNextUrl);
            String bizData = JSON.toJSONString(txnLimitCfg);
            int length = bizData.length();
            if (bizData.length() > 12000) {
                throw new RedpException("业务数据过长，请联系管理员！");
            }
            String bizData1;
            String bizData2 = "";
            String bizData3 = "";
            if (bizData.length() > 4000) {
                bizData1 = bizData.substring(0, 3999);
                bizData2 = bizData.substring(4000);
            } else {
                bizData1 = bizData;
            }
            if (bizData2.length() > 4000) {
                bizData2 = bizData2.substring(0, 3999);
                bizData3 = bizData.substring(8000);
            }
            tmp.setMchntNo(txnCfginfo.getMcNo());
            tmp.setMchntName(txnCfginfo.getMcName());
            tmp.setTermNo(txnCfginfo.getMcTermNo());
            tmp.setBizData1(bizData1);
            tmp.setBizData2(bizData2);
            tmp.setBizData3(bizData3);
            tmp.setDetailFlag("Y");
            tmp.setMasterKey(uuid);
            tmp.setRealId(txnLimitCfg.getId());
            bizTmpList.add(tmp);
        }
        BizTmp bizTmp = coverBizTmp(TxnDatalist.get(0), oprType, oprMenuId, oprMenuName, org.getOrgCode(), user.getInstId(), txnCfginfo.getBizStatus(), txnCfginfo.getAuditStatus(), webNextUrl);
        bizTmp.setBizData1("明细有" + bizTmpList.size() + "条");
        bizTmp.setMchntNo(txnCfginfo.getMcNo());
        bizTmp.setMchntName(txnCfginfo.getMcName());
        bizTmp.setTermNo(txnCfginfo.getMcTermNo());
        bizTmp.setRealId(uuid);
        bizTmp.setDetailFlag("N");
        bizTmpList.add(bizTmp);
        for (BizTmp bean: bizTmpList
             ) {
            bizTmpService.save(bean);
        }

    }

    private BizTmp coverBizTmp(BTxnLimitCfg entity, String bizOpr, String menuId, String menuName, String orgCode, String instId, String bizStatus, String auditStatus, String webNextUrlStr) {
        BizTmp bizTmp = new BizTmp();
        String ename = entity.getClass().getAnnotation(TableName.class).value();
        String cname = entity.getClass().getAnnotation(ApiModel.class).description();
        bizTmp.setRealId(entity.getId());
        bizTmp.setBizData1("");
        bizTmp.setBizData2("");
        bizTmp.setBizData3("");
        bizTmp.setBizOpr(bizOpr);
        bizTmp.setOprId(entity.getOprId());
        bizTmp.setCreateTime(entity.getCreateTime());
        bizTmp.setLastOprId(entity.getLastOprId());
        bizTmp.setLastUpdateTime(entity.getLastUpdateTime());
        bizTmp.setOprMenuId(menuId);
        bizTmp.setOprMenuName(menuName);
        bizTmp.setOprTableCname(cname);
        bizTmp.setOprTableEname(ename);
        bizTmp.setManageInstId(orgCode);
        bizTmp.setInstId(instId);
        bizTmp.setBizStatus(bizStatus);
        bizTmp.setAuditStatus(auditStatus);
        bizTmp.setWebNextUrl(webNextUrlStr);

        return bizTmp;
    }

    private void saveQuotaBizHis(BTxnLimitCfg txnCfginfo,BTxnLimitCfg oldTxnCfginfo, String bizOpr) throws RedpException {

        List<BTxnLimitCfg> txnLimitCfgsOld=new ArrayList<>();
        UpmpUserInfoVO user = RedpUpmpUtil.getCurrentUser(txnCfginfo.getInstId());
        UpmpOrganization org = upmpOrganizationService.getOrgByCode(user.getOrgCode(), user.getInstId());
        List<BTxnLimitCfg> txnLimitCfgs = coverBizData(txnCfginfo);
        if(BizOprEnum.OPR_ADD.getType().equals(bizOpr)){
            for (BTxnLimitCfg bean : txnLimitCfgs) {
                txnLimitCfgsOld.add(new BTxnLimitCfg());
            }
        }else {
            txnLimitCfgsOld = coverBizData(oldTxnCfginfo);
        }

        List<String> realIds = new ArrayList<>();
        List<Object> entitys = new ArrayList<>();
        List<Object> entitysOld = new ArrayList<>();
        List<String> bizOprs = new ArrayList<>();
        for (BTxnLimitCfg bean : txnLimitCfgs) {
            realIds.add(CommonUtils.getUUID());
            entitys.add(bean);
            bizOprs.add(bizOpr);
        }
        for (BTxnLimitCfg bean : txnLimitCfgsOld) {

            entitysOld.add(bean);

        }

        bizHisService.saveBizHisList(entitys, entitysOld, user, org.getInstId(), bizOprs,
                txnLimitCfgs.get(0).getCreateTime(), oprMenuId, oprMenuName, realIds,null,null,null);

    }

    private List<BTxnLimitCfg> coverBizData(BTxnLimitCfg txnCfginfo) {
        if ("12".equals(txnCfginfo.getLimitType())) {
            txnCfginfo.setLimitInst(txnCfginfo.getMcNo()+"|"+txnCfginfo.getMcTermNo());
        }else if("11".equals(txnCfginfo.getLimitType())){
            txnCfginfo.setLimitInst(txnCfginfo.getMcNo());
        }
        List<BTxnLimitCfg> txnLimitCfgs = new ArrayList<>();
        BTxnLimitCfg notDiff = new BTxnLimitCfg();
        notDiff.setSingleLimitMaxAmt("");
        notDiff.setDayLimitAmt(txnCfginfo.getDayLimitAmt());
        notDiff.setMonthLimitAmt(txnCfginfo.getMonthLimitAmt());

        notDiff.setStatus(txnCfginfo.getStatus());
        notDiff.setAuditStatus(txnCfginfo.getAuditStatus());
        notDiff.setOprId(txnCfginfo.getOprId());
        notDiff.setCreateTime(txnCfginfo.getCreateTime());
        notDiff.setLastOprId(txnCfginfo.getLastOprId());
        notDiff.setLastUpdateTime(txnCfginfo.getLastUpdateTime());

        notDiff.setLimitAcctType("*");
        notDiff.setInstId(txnCfginfo.getInstId());
        notDiff.setLimitType(txnCfginfo.getLimitType());
        notDiff.setLimitInst(txnCfginfo.getLimitInst());
        notDiff.setId(txnCfginfo.getNotDiffAcctId());

        txnLimitCfgs.add(notDiff);

        BTxnLimitCfg credCfg = new BTxnLimitCfg();
        credCfg.setSingleLimitMaxAmt(txnCfginfo.getSingleLimitCreditMaxAmt());
        credCfg.setDayLimitAmt(txnCfginfo.getDayLimitCreditAmt());
        credCfg.setMonthLimitAmt(txnCfginfo.getMonthLimitCreditAmt());

        credCfg.setStatus(txnCfginfo.getStatus());
        credCfg.setAuditStatus(txnCfginfo.getAuditStatus());
        credCfg.setOprId(txnCfginfo.getOprId());
        credCfg.setCreateTime(txnCfginfo.getCreateTime());
        credCfg.setLastOprId(txnCfginfo.getLastOprId());
        credCfg.setLastUpdateTime(txnCfginfo.getLastUpdateTime());

        credCfg.setLimitAcctType("21");
        credCfg.setInstId(txnCfginfo.getInstId());
        credCfg.setLimitType(txnCfginfo.getLimitType());
        credCfg.setLimitInst(txnCfginfo.getLimitInst());
        credCfg.setId(txnCfginfo.getCreditId());

        txnLimitCfgs.add(credCfg);

        BTxnLimitCfg loanCfg = new BTxnLimitCfg();
        loanCfg.setSingleLimitMaxAmt(txnCfginfo.getSingleLimitLoanMaxAmt());
        loanCfg.setDayLimitAmt(txnCfginfo.getDayLimitLoanAmt());
        loanCfg.setMonthLimitAmt(txnCfginfo.getMonthLimitLoanAmt());

        loanCfg.setStatus(txnCfginfo.getStatus());
        loanCfg.setAuditStatus(txnCfginfo.getAuditStatus());
        loanCfg.setOprId(txnCfginfo.getOprId());
        loanCfg.setCreateTime(txnCfginfo.getCreateTime());
        loanCfg.setLastOprId(txnCfginfo.getLastOprId());
        loanCfg.setLastUpdateTime(txnCfginfo.getLastUpdateTime());

        loanCfg.setLimitAcctType("20");
        loanCfg.setInstId(txnCfginfo.getInstId());
        loanCfg.setLimitType(txnCfginfo.getLimitType());
        loanCfg.setLimitInst(txnCfginfo.getLimitInst());
        loanCfg.setId(txnCfginfo.getLoanId());

        txnLimitCfgs.add(loanCfg);
        if ("11".equals(txnCfginfo.getLimitType())) {
            //商户退货限额不分账户类型
            BTxnLimitCfg refundCfg = new BTxnLimitCfg();
            refundCfg.setSingleLimitMaxAmt("");
            refundCfg.setDayRefundLimitAmt(txnCfginfo.getRefundDayLimitAmt());
            refundCfg.setMonthLimitAmt("");

            refundCfg.setStatus(txnCfginfo.getStatus());
            refundCfg.setAuditStatus(txnCfginfo.getAuditStatus());
            refundCfg.setOprId(txnCfginfo.getOprId());
            refundCfg.setCreateTime(txnCfginfo.getCreateTime());
            refundCfg.setLastOprId(txnCfginfo.getLastOprId());
            refundCfg.setLastUpdateTime(txnCfginfo.getLastUpdateTime());

            refundCfg.setLimitAcctType("*");
            refundCfg.setInstId(txnCfginfo.getInstId());
            refundCfg.setLimitType("14");
            refundCfg.setLimitInst(txnCfginfo.getLimitInst());
            refundCfg.setId(txnCfginfo.getRefundNotDiffAcctId());

            txnLimitCfgs.add(refundCfg);
            //商户退货限额借记账户
            BTxnLimitCfg refundLoanCfg = new BTxnLimitCfg();
            refundLoanCfg.setSingleRefundLimitAmt(txnCfginfo.getRefundSingleLimitLoanMaxAmt());
            refundLoanCfg.setDayRefundLimitAmt(txnCfginfo.getRefundDayLimitLoanAmt());
            refundLoanCfg.setMonthLimitAmt("");

            refundLoanCfg.setStatus(txnCfginfo.getStatus());
            refundLoanCfg.setAuditStatus(txnCfginfo.getAuditStatus());
            refundLoanCfg.setOprId(txnCfginfo.getOprId());
            refundLoanCfg.setCreateTime(txnCfginfo.getCreateTime());
            refundLoanCfg.setLastOprId(txnCfginfo.getLastOprId());
            refundLoanCfg.setLastUpdateTime(txnCfginfo.getLastUpdateTime());

            refundLoanCfg.setLimitAcctType("20");
            refundLoanCfg.setInstId(txnCfginfo.getInstId());
            refundLoanCfg.setLimitType("14");
            refundLoanCfg.setLimitInst(txnCfginfo.getLimitInst());
            refundLoanCfg.setId(txnCfginfo.getRefundLoanId());

            txnLimitCfgs.add(refundLoanCfg);
            //商户退货限额贷记账户
            BTxnLimitCfg refundCreditCfg = new BTxnLimitCfg();
            refundCreditCfg.setSingleRefundLimitAmt(txnCfginfo.getRefundSingleLimitCredMaxAmt());
            refundCreditCfg.setDayRefundLimitAmt(txnCfginfo.getRefundDayLimitCredAmt());
            refundCreditCfg.setMonthLimitAmt("");

            refundCreditCfg.setStatus(txnCfginfo.getStatus());
            refundCreditCfg.setAuditStatus(txnCfginfo.getAuditStatus());
            refundCreditCfg.setOprId(txnCfginfo.getOprId());
            refundCreditCfg.setCreateTime(txnCfginfo.getCreateTime());
            refundCreditCfg.setLastOprId(txnCfginfo.getLastOprId());
            refundCreditCfg.setLastUpdateTime(txnCfginfo.getLastUpdateTime());

            refundCreditCfg.setLimitAcctType("21");
            refundCreditCfg.setInstId(txnCfginfo.getInstId());
            refundCreditCfg.setLimitType("14");
            refundCreditCfg.setLimitInst(txnCfginfo.getLimitInst());
            refundCreditCfg.setId(txnCfginfo.getRefundCreditId());

            txnLimitCfgs.add(refundCreditCfg);
        }
        return txnLimitCfgs;
    }

    /**
     * 保存商户限额信息
     */
    private void saveMerchantQutaInfo(BTxnLimitCfg txnCfginfo) throws RedpException {
        try {
            String limitType = txnCfginfo.getLimitType();
            String instId = txnCfginfo.getInstId();
            String limitInst = txnCfginfo.getLimitInst();
            if (StringUtils.isBlank(limitType) || StringUtils.isBlank(instId) || StringUtils.isBlank(limitInst)) {
                log.error("请求数据有误:[{}]", limitType + "|" + instId + "|" + limitInst);
                throw new RedpException("请求数据有误");
            }
             QueryWrapper queryWrapper=new QueryWrapper();

            queryWrapper.eq("limit_Type", limitType);
            queryWrapper.eq("inst_Id", instId);
            queryWrapper.eq("limit_Inst", limitInst);
            String mchntNo = txnCfginfo.getMchntNo();
            if (StringUtils.isBlank(mchntNo)){
                mchntNo=txnCfginfo.getMcNo();
            }
            List resultListCount = merchantBaseInfoMapper.selectList(queryWrapper);
            if (resultListCount.size() > 0) {
                log.error("商户限额信息已存在:[{}]", txnCfginfo.getMcNo());
                throw new RedpException(mchntNo + "商户限额信息已存在");
            }

            UpmpUserInfoVO user = RedpUpmpUtil.getCurrentUser(instId);
            BTxnLimitCfg sqlBtxn=new BTxnLimitCfg();
            //商户限额
            sqlBtxn.setInstId(instId).
                    setLimitInst(txnCfginfo.getMchntNo())
                    .setLimitType( txnCfginfo.getLimitType())//商户限额 “11”
                    .setLimitAcctType("*")
                    .setSingleLimitMaxAmt(txnCfginfo.getSingleLimitMaxAmt())
                    .setDayLimitAmt(txnCfginfo.getDayLimitAmt())
                    .setMonthLimitAmt( txnCfginfo.getMonthLimitAmt())
                    .setStatus(txnCfginfo.getStatus())
                    .setAuditStatus( txnCfginfo.getAuditStatus())
                    .setOprId(txnCfginfo.getOprId())
                    .setCrtOrgId(txnCfginfo.getCrtOrgId())
                    .setCreateTime(txnCfginfo.getCreateTime())
                    .setId(txnCfginfo.getNotDiffAcctId());
        merchantBaseInfoMapper.insert(sqlBtxn);


            //借记限额
            sqlBtxn.setSingleLimitMaxAmt(txnCfginfo.getSingleLimitLoanMaxAmt());
            sqlBtxn.setDayLimitAmt(txnCfginfo.getDayLimitLoanAmt());
            sqlBtxn.setMonthLimitAmt(txnCfginfo.getMonthLimitLoanAmt());
            sqlBtxn.setLimitAcctType("20");//20-借记账户(包括本行、他行借记账户)  21-贷记账户(包括本行、他行贷记账户)
            sqlBtxn.setId( txnCfginfo.getLoanId());
            merchantBaseInfoMapper.insert(sqlBtxn);

            //贷记限额
            sqlBtxn.setSingleLimitMaxAmt(txnCfginfo.getSingleLimitCreditMaxAmt());
            sqlBtxn.setDayLimitAmt(txnCfginfo.getDayLimitCreditAmt());
            sqlBtxn.setMonthLimitAmt(txnCfginfo.getMonthLimitCreditAmt());
            sqlBtxn.setLimitAcctType("21");
            sqlBtxn.setId( txnCfginfo.getCreditId());
            merchantBaseInfoMapper.insert(sqlBtxn);

            //退款限额
            BTxnLimitCfg queryRef=new BTxnLimitCfg();
            queryRef.setInstId(instId);
            queryRef.setLimitType( "14");//14-商户退货限额
            queryRef.setLimitInst(txnCfginfo.getMchntNo());
            queryRef.setLimitAcctType( "*");   //"*" 不分账户类型

            queryRef.setSingleLimitMaxAmt( "");
            queryRef.setDayLimitAmt( txnCfginfo.getRefundDayLimitAmt());
            queryRef.setMonthLimitAmt( "");

            queryRef.setStatus(txnCfginfo.getStatus());
            queryRef.setAuditStatus( txnCfginfo.getAuditStatus());
            queryRef.setOprId(txnCfginfo.getOprId());
            queryRef.setCrtOrgId(txnCfginfo.getCrtOrgId());
            queryRef.setCreateTime( txnCfginfo.getCreateTime());
            queryRef.setId(txnCfginfo.getRefundNotDiffAcctId());
            merchantBaseInfoMapper.insert(queryRef);

            //贷记
            queryRef.setLimitAcctType("21");//"*" 不分账户类型
            queryRef.setSingleLimitMaxAmt(txnCfginfo.getRefundSingleLimitCredMaxAmt());
            queryRef.setDayLimitAmt( txnCfginfo.getRefundDayLimitCredAmt());
            queryRef.setId(txnCfginfo.getRefundCreditId());
            merchantBaseInfoMapper.insert(queryRef);
            //借记
            queryRef.setLimitAcctType("20");//"*" 不分账户类型
            queryRef.setSingleLimitMaxAmt(txnCfginfo.getRefundSingleLimitLoanMaxAmt());
            queryRef.setDayLimitAmt( txnCfginfo.getRefundDayLimitLoanAmt());
            queryRef.setId(txnCfginfo.getRefundLoanId());
            merchantBaseInfoMapper.insert(queryRef);
        } catch (Exception e) {
            // TODO: handle exception
            log.error("交易出现异常，异常信息：" + e.getMessage());
            throw new RedpException("交易出现异常，异常信息：" + e.getMessage());
        }
    }


    //----------------停用 启用 注销


    @Transactional(value = "transactionManager")
    public void stopMcLevelQuota(HttpServletRequest request,BTxnLimitCfg reqLimit) throws RedpException {
        String limitType = request.getParameter("limitType");
        BTxnLimitCfg txnCfginfo = null;
        if ("11".equals(limitType)) {
            txnCfginfo = getMcQuotaDetail(reqLimit);
        } else if ("12".equals(limitType)) {
            txnCfginfo = getTermQuotaById(reqLimit);
        } else {
            throw new RedpException("限额类型不匹配");
        }
        BTxnLimitCfg oldData = new BTxnLimitCfg();
        txnCfginfo.setInstId(reqLimit.getInstId());
        BeanUtils.copyProperties(txnCfginfo,oldData);
        UpmpUserInfoVO user = RedpUpmpUtil.getCurrentUser(reqLimit.getInstId());
        upmpOrganizationService.getOrgByCode(user.getOrgCode(), user.getInstId());
        UpmpPrivilegeCheck privilegeCheckByPrivilegeCode = authPrivilegeCheckService.getPrivilegeCheckByPrivilegeCode(reqLimit.getInstId(), "merchantLevelManager:stop");


        if (null == privilegeCheckByPrivilegeCode) {
            throw new RedpException("获取审核信息失败");
        }

        boolean checked = BusinessContainer.YES.equals(privilegeCheckByPrivilegeCode.getChecked());
        if (checked) {
            //       txnCfginfo.setStatus("N"); //Y 启用 N停用
            //      txnCfginfo.setBizStatus(BizDataStatusEnum.STATUS_DRAFT.getType());
            txnCfginfo.setAuditStatus(BizDataAuditStatusEnum.AUDIT_STATUS_STOP_CHECKING.getType());
            txnCfginfo.setLastOprId(user.getOprId());
            txnCfginfo.setLastUpdateTime(DateUtils.formatDate(new Date(), DateUtils.DEFAULT_TIME_FORMAT));

            //修正式表
            editMerchantQutaAuthStatus(txnCfginfo);
            //修改临时表
            saveBizTmp(txnCfginfo, BizOprEnum.OPR_STOP.getType());
        } else {
            txnCfginfo.setStatus("N"); //Y 启用 N停用
            txnCfginfo.setBizStatus(BizDataStatusEnum.STATUS_STOPED.getType());
            txnCfginfo.setAuditStatus(BizDataAuditStatusEnum.AUDIT_STATUS_STOP_PASS.getType());
            txnCfginfo.setOprId(user.getOprId());
            txnCfginfo.setCreateTime(DateUtils.formatDate(new Date(), DateUtils.DEFAULT_TIME_FORMAT));
            //保存正式表
            editMerchantQutaInfo(txnCfginfo);
            //保存历史表
            saveQuotaBizHis(txnCfginfo,oldData, BizOprEnum.OPR_STOP.getType());
        }
    }
    /**
     * 审核通过修改商户限额信息
     *
     * @param txnCfginfo
     */
    private void editMerchantQutaInfo(BTxnLimitCfg txnCfginfo) throws RedpException {
        try {
            BTxnLimitCfg bTxnLimitCfg=new BTxnLimitCfg();
            BeanUtils.copyProperties(txnCfginfo,bTxnLimitCfg);
            //不分账户  商户限额
            bTxnLimitCfg.setSingleLimitMaxAmt("");
           QueryWrapper queryWrapper=new QueryWrapper();
           queryWrapper.eq("id", txnCfginfo.getNotDiffAcctId());

            int mcCount = merchantBaseInfoMapper.update(bTxnLimitCfg, queryWrapper);

            //贷记
            bTxnLimitCfg.setSingleLimitMaxAmt(txnCfginfo.getSingleLimitCreditMaxAmt());
            bTxnLimitCfg.setDayLimitAmt( txnCfginfo.getDayLimitCreditAmt());
            bTxnLimitCfg.setMonthLimitAmt( txnCfginfo.getMonthLimitCreditAmt());
            queryWrapper.clear();

            queryWrapper.eq("id", txnCfginfo.getCreditId());

            int mcCrCount = merchantBaseInfoMapper.update(bTxnLimitCfg, queryWrapper);
            //借记
            bTxnLimitCfg.setSingleLimitMaxAmt(txnCfginfo.getSingleLimitLoanMaxAmt());
            bTxnLimitCfg.setDayLimitAmt( txnCfginfo.getDayLimitLoanAmt());
            bTxnLimitCfg.setMonthLimitAmt( txnCfginfo.getMonthLimitLoanAmt());
            queryWrapper.clear();

            queryWrapper.eq("id", txnCfginfo.getLoanId());
            int mcLonCount = merchantBaseInfoMapper.update(bTxnLimitCfg, queryWrapper);

            if ("11".equals(txnCfginfo.getLimitType())) {
                //不分账户 退款限额
                bTxnLimitCfg.setSingleLimitMaxAmt("");
                bTxnLimitCfg.setDayLimitAmt(txnCfginfo.getRefundDayLimitAmt());
                bTxnLimitCfg.setMonthLimitAmt("");
                bTxnLimitCfg.setStatus(txnCfginfo.getStatus());
                bTxnLimitCfg.setAuditStatus(txnCfginfo.getAuditStatus());
                bTxnLimitCfg.setLastOprId(txnCfginfo.getLastOprId());
                bTxnLimitCfg.setLastUpdateTime(txnCfginfo.getLastUpdateTime());
                bTxnLimitCfg.setAuditRefuseReason(txnCfginfo.getAuditRefuseReason());
                bTxnLimitCfg.setLimitInst(txnCfginfo.getMcNo());
                bTxnLimitCfg.setLimitType("14");
                bTxnLimitCfg.setLimitAcctType("*");
                QueryWrapper queryWrapper1=new QueryWrapper();
                queryWrapper1.eq("id", txnCfginfo.getRefundNotDiffAcctId());
                int refCount = merchantBaseInfoMapper.update(bTxnLimitCfg, queryWrapper1);


                //贷记
                if(StringUtils.isBlank(txnCfginfo.getRefcreSingleLimitCredMaxAmt())){
                    bTxnLimitCfg.setSingleLimitMaxAmt(txnCfginfo.getReSingleLimitCredMaxAmt());
                }else {
                    bTxnLimitCfg.setSingleLimitMaxAmt(txnCfginfo.getRefundSingleLimitCredMaxAmt());
                }
                bTxnLimitCfg.setDayLimitAmt( txnCfginfo.getRefundDayLimitCredAmt());
                bTxnLimitCfg.setMonthLimitAmt( "");
                bTxnLimitCfg.setLimitAcctType("21");
                queryWrapper1.clear();
                queryWrapper1.eq("id", txnCfginfo.getRefundCreditId());
                int refCrCount = merchantBaseInfoMapper.update(bTxnLimitCfg, queryWrapper1);

                //借记
                if(StringUtils.isBlank(txnCfginfo.getRefundSingleLimitLoanMaxAmt())){
                    bTxnLimitCfg.setSingleLimitMaxAmt(txnCfginfo.getReSingleLimitLoanMaxAmt());
                }else {
                    bTxnLimitCfg.setSingleLimitMaxAmt(txnCfginfo.getRefundSingleLimitLoanMaxAmt());
                }
                bTxnLimitCfg.setLimitAcctType("20");
                bTxnLimitCfg.setDayLimitAmt( txnCfginfo.getRefundDayLimitLoanAmt());
                bTxnLimitCfg.setMonthLimitAmt( "");
                queryWrapper1.clear();
                queryWrapper1.eq("id", txnCfginfo.getRefundLoanId());
                int reflonCount = merchantBaseInfoMapper.update(bTxnLimitCfg, queryWrapper1);
            }
        } catch (Exception e) {
            // TODO: handle exception
            log.error("交易出现异常，异常信息：" + e.getMessage());
            throw new RedpException("交易出现异常，异常信息：" + e.getMessage());
        }
    }

    /**
     * 修改审核状态
     */
    private void editMerchantQutaAuthStatus(BTxnLimitCfg txnCfginfo) throws RedpException {
        try {

            QueryWrapper queryWrapper=new QueryWrapper();
            queryWrapper.eq("id", txnCfginfo.getNotDiffAcctId());
            Boolean mcCount=merchantBaseInfoService.update(txnCfginfo, queryWrapper);

            //贷记
        queryWrapper.clear();
        queryWrapper.eq("id", txnCfginfo.getCreditId());
            Boolean mcCrCount =    merchantBaseInfoService.update(txnCfginfo, queryWrapper);

            //借记
            queryWrapper.clear();
            queryWrapper.eq("id", txnCfginfo.getLoanId());
            Boolean mcLonCount =    merchantBaseInfoService.update(txnCfginfo, queryWrapper);
            if ("11".equals(txnCfginfo.getLimitType())) {
                //不分账户 退款限额
                queryWrapper.clear();
                queryWrapper.eq("id",  txnCfginfo.getRefundNotDiffAcctId());
                Boolean refCount =    merchantBaseInfoService.update(txnCfginfo, queryWrapper);

                //贷记
                queryWrapper.clear();
                queryWrapper.eq("id",   txnCfginfo.getRefundCreditId());
                Boolean refCrCount =    merchantBaseInfoService.update(txnCfginfo, queryWrapper);

                //借记
                queryWrapper.clear();
                queryWrapper.eq("id",   txnCfginfo.getRefundLoanId());
                Boolean reflonCount =    merchantBaseInfoService.update(txnCfginfo, queryWrapper);
            }
        } catch (Exception e) {
            // TODO: handle exception
            log.error("交易出现异常，异常信息：" + e.getMessage());
            throw new RedpException("交易出现异常，异常信息：" + e.getMessage());
        }
    }

    public BTxnLimitCfg getTermQuotaById(BTxnLimitCfg request) throws RedpException {
        try {
            String notDiffAcctId = request.getNotDiffAcctId();
            String creditId = request.getCreditId();
            String loanId = request.getLoanId();

            if (StringUtils.isBlank(notDiffAcctId) || StringUtils.isBlank(creditId) || StringUtils.isBlank(loanId)) {
                log.error("请求数据有误");
                throw new RedpException("请求数据有误");
            }
            List<BTxnLimitCfg> mcQuotaDetail = new ArrayList<>();
            List<BTxnLimitCfg> resultList = merchantBaseInfoMapper.getTermQuotaById(notDiffAcctId, loanId, creditId);
            if (resultList.size() > 0) {
             //   mcQuotaDetail = mapTxnLimitCfgVoList(resultList);
                return resultList.get(0);
            } else {
                throw new RedpException("获取商户级限额详情时系统异常");
            }
        } catch (Exception e) {
            // TODO: handle exception
            log.error("交易出现异常，异常信息：" + e.getMessage());
            throw new RedpException("交易出现异常，异常信息：" + e.getMessage());
        }
    }
    /**
     * 获取商户级限额详情数据
     */

    public BTxnLimitCfg getMcQuotaDetail(BTxnLimitCfg request) throws RedpException {
        try {
            String notDiffAcctId = request.getNotDiffAcctId();
            String creditId = request.getCreditId();
            String loanId = request.getLoanId();
            String refundDiffAcctId = request.getRefundDiffAcctId();
            if (StringUtils.isBlank(refundDiffAcctId)){
                refundDiffAcctId=request.getRefundNotDiffAcctId();
            }
            String refundCreditId = request.getRefundCreditId();
            String refundLoanId = request.getRefundLoanId();
            if (StringUtils.isBlank(notDiffAcctId) || StringUtils.isBlank(creditId) || StringUtils.isBlank(loanId)
                    || StringUtils.isBlank(refundDiffAcctId) || StringUtils.isBlank(refundCreditId) || StringUtils.isBlank(refundLoanId)) {
                log.error("请求数据有误");
                throw new RedpException("请求数据有误");
            }
            List<BTxnLimitCfg> mcQuotaDetail = new ArrayList<>();
            List<BTxnLimitCfg> resultList = merchantBaseInfoMapper.getMcQuotaDetail(notDiffAcctId, loanId, creditId, refundDiffAcctId, refundLoanId, refundCreditId);
            if (resultList.size() == 1) {
                //mcQuotaDetail = mapTxnLimitCfgVoList(resultList);
                return resultList.get(0);
            } else if (resultList.size() > 1) {
                log.error("获取 数据不唯一");
                throw new RedpException("获取 数据不唯一");
            } else {
                throw new RedpException("获取 数据不唯一");
            }
        } catch (Exception e) {
            // TODO: handle exception
            log.error("交易出现异常，异常信息：" + e.getMessage());
            throw new RedpException("交易出现异常，异常信息：" + e.getMessage());
        }
    }

    /**
     * 创建终端限额信息
     *
     * @param txnCfginfo
     * @param request
     */

    @Transactional(value = "transactionManager")
    public void saveMcTremQuota(BTxnLimitCfg txnCfginfo, HttpServletRequest request) throws RedpException {

        String id = CommonUtils.getUUID();
        txnCfginfo.setNotDiffAcctId(id);
        UpmpUserInfoVO user = RedpUpmpUtil.getCurrentUser(txnCfginfo.getInstId());
        UpmpOrganization org = upmpOrganizationService.getOrgByCode(user.getOrgCode(), txnCfginfo.getInstId());

        UpmpPrivilegeCheck privilegeCheckByPrivilegeCode = authPrivilegeCheckService.getPrivilegeCheckByPrivilegeCode(txnCfginfo.getInstId(), "merchantLevelManager:add");
        if (null == privilegeCheckByPrivilegeCode) {
            throw new RedpException("获取审核信息失败");
        }
        txnCfginfo.setNotDiffAcctId(CommonUtils.getUUID());
        txnCfginfo.setCreditId(CommonUtils.getUUID());
        txnCfginfo.setLoanId(CommonUtils.getUUID());
//        if(user.isAdmin()){
//            String instId = request.getParameter("instId");
//            UpmpOrganization headOrg = upmpOrganizationService.getHeadOrgByCode(instId);
//            String crtOrgId = headOrg == null ? user.getOrgCode() : headOrg.getOrgCode();
//            txnCfginfo.setInstId(instId);
//            txnCfginfo.setCrtOrgId(crtOrgId);
//        }else {
//            txnCfginfo.setInstId(user.getInstId());
//            txnCfginfo.setCrtOrgId(org.getOrgCode());
//        }
        String instId = request.getParameter("instId");
        UpmpOrganization headOrg = upmpOrganizationService.getHeadOrgByCode(instId);
        String crtOrgId = headOrg == null ? user.getOrgCode() : headOrg.getOrgCode();
        txnCfginfo.setInstId(instId);
        txnCfginfo.setCrtOrgId(crtOrgId);
        String mcNo=txnCfginfo.getMcNo();
        if (StringUtils.isBlank(mcNo)){
            mcNo=txnCfginfo.getMchntNo();
            txnCfginfo.setMcNo(mcNo);
        }
        txnCfginfo.setLimitInst(mcNo+"|"+txnCfginfo.getMcTermNo());
        boolean checked = BusinessContainer.YES.equals(privilegeCheckByPrivilegeCode.getChecked());
        if (checked) {
            //保存正式表

            txnCfginfo.setLimitType("12"); //12-商户终端限额

            txnCfginfo.setBizStatus(BizDataStatusEnum.STATUS_DRAFT.getType());
            txnCfginfo.setAuditStatus(BizDataAuditStatusEnum.AUDIT_STATUS_ADD_CHECKING.getType());
            txnCfginfo.setOprId(user.getOprId());
            txnCfginfo.setCreateTime(DateUtils.formatDate(new Date(), DateUtils.DEFAULT_TIME_FORMAT));
            txnCfginfo.setStatus("N");
            saveMerchantTermQutaInfo(txnCfginfo);

            //保存零时表
            saveBizTmp(txnCfginfo, BizOprEnum.OPR_ADD.getType());
        } else if (!checked) {

            txnCfginfo.setLimitType("12"); //12-商户终端限额
            txnCfginfo.setStatus("Y"); //Y 启用 N停用
            txnCfginfo.setBizStatus(BizDataStatusEnum.STATUS_NORMAL.getType());
            txnCfginfo.setAuditStatus(BizDataAuditStatusEnum.AUDIT_STATUS_ADD_PASS.getType());
            txnCfginfo.setOprId(user.getOprId());
            txnCfginfo.setCreateTime(DateUtils.formatDate(new Date(), DateUtils.DEFAULT_TIME_FORMAT));
            saveMerchantTermQutaInfo(txnCfginfo);

            saveQuotaBizHis(txnCfginfo,null, BizOprEnum.OPR_ADD.getType());
        }

    }

    /**
     * 修改终端限额数据
     *
     * @param txnCfginfo
     */

    @Transactional(value = "transactionManager")
    public void editTmQuota(BTxnLimitCfg txnCfginfo) throws RedpException {
        try {
            BTxnLimitCfg oldData=new BTxnLimitCfg();
            if ("11".equals(txnCfginfo.getLimitType())) {
                oldData = getMcQuotaDetail(txnCfginfo);

            } else if ("12".equals(txnCfginfo.getLimitType())) {
                //获取终端限额数据
                oldData=getTermQuotaById(txnCfginfo);
            } else {
                throw new RedpException("限额信息参数有误");
            }
            txnCfginfo.setOprId(oldData.getOprId());
            txnCfginfo.setCreateTime(oldData.getCreateTime());
            UpmpUserInfoVO user = RedpUpmpUtil.getCurrentUser(txnCfginfo.getInstId());
            UpmpOrganization org = upmpOrganizationService.getOrgByCode(user.getOrgCode(), user.getInstId());

            UpmpPrivilegeCheck privilegeCheckByPrivilegeCode = authPrivilegeCheckService.getPrivilegeCheckByPrivilegeCode(txnCfginfo.getInstId(), "merchantLevelManager:edit");
            if (null == privilegeCheckByPrivilegeCode) {
                throw new RedpException("获取审核信息失败");
            }
            txnCfginfo.setStatus(oldData.getStatus());
            boolean checked = BusinessContainer.YES.equals(privilegeCheckByPrivilegeCode.getChecked());
            if (checked) {
                //修改正式表
                txnCfginfo.setLimitType("12"); //12-商户终端限额

                txnCfginfo.setBizStatus(BizDataStatusEnum.STATUS_DRAFT.getType());
                txnCfginfo.setAuditStatus(BizDataAuditStatusEnum.AUDIT_STATUS_UPD_CHECKING.getType());
                txnCfginfo.setLastOprId(user.getOprId());
                txnCfginfo.setLastUpdateTime(DateUtils.formatDate(new Date(), DateUtils.DEFAULT_TIME_FORMAT));
                editMerchantQutaAuthStatus(txnCfginfo);
                //修改临时表
                saveBizTmp(txnCfginfo, BizOprEnum.OPR_UPDATE.getType());
            } else if (!checked) {
                txnCfginfo.setLimitType("12"); //12-商户终端限额

                txnCfginfo.setBizStatus(BizDataStatusEnum.STATUS_NORMAL.getType());
                txnCfginfo.setAuditStatus(BizDataAuditStatusEnum.AUDIT_STATUS_UPD_PASS.getType());
                txnCfginfo.setLastOprId(user.getOprId());
                txnCfginfo.setLastUpdateTime(DateUtils.formatDate(new Date(), DateUtils.DEFAULT_TIME_FORMAT));
                editMerchantQutaInfo(txnCfginfo);

                //保存历史表
                saveQuotaBizHis(txnCfginfo,oldData, BizOprEnum.OPR_UPDATE.getType());
            }


        } catch (Exception e) {
            log.error("修改商户终端限额配置时系统异常:[{}]", e);
            throw new RedpException("修改商户终端限额配置时系统异常");
        }
    }

    /**
     * 保存终端限额信息
     */
    private void saveMerchantTermQutaInfo(BTxnLimitCfg txnCfginfo) throws RedpException {
        try {
            String limitType = txnCfginfo.getLimitType();
            String instId = txnCfginfo.getInstId();
            String limitInst = txnCfginfo.getLimitInst();
            if (StringUtils.isBlank(limitType) || StringUtils.isBlank(instId) || StringUtils.isBlank(limitInst)) {
                log.error("请求数据有误:[{}]", limitType + "|" + instId + "|" + limitInst);
                throw new RedpException("请求数据有误");
            }
            QueryWrapper queryWrapper=new QueryWrapper();
            queryWrapper.eq("LIMIT_ACCT_TYPE", '*');
            queryWrapper.eq("LIMIT_TYPE", limitType);
            queryWrapper.eq("LIMIT_INST", limitInst);
            queryWrapper.eq("INST_ID", instId);

            List resultListCount = merchantBaseInfoMapper.selectList(queryWrapper);

            if (resultListCount.size() > 0) {
                log.error("限额信息已存在:[{}]", txnCfginfo.getMcNo());
                throw new RedpException(txnCfginfo.getMcNo() + "限额信息已存在");
            }

            UpmpUserInfoVO user = RedpUpmpUtil.getCurrentUser(instId);
            //商户限额
                BTxnLimitCfg bTxnLimitCfgMC=new BTxnLimitCfg();
                bTxnLimitCfgMC.setInstId(instId);
                bTxnLimitCfgMC.setLimitType(txnCfginfo.getLimitType());
                bTxnLimitCfgMC.setLimitInst(txnCfginfo.getMcNo() + "|" + txnCfginfo.getMcTermNo());
                bTxnLimitCfgMC.setLimitAcctType("*");//"*" 不分账户类型
                bTxnLimitCfgMC.setSingleLimitMaxAmt(txnCfginfo.getSingleLimitMaxAmt());

            bTxnLimitCfgMC.setDayLimitAmt(txnCfginfo.getDayLimitAmt());
            bTxnLimitCfgMC.setMonthLimitAmt(txnCfginfo.getMonthLimitAmt());

            bTxnLimitCfgMC.setStatus(txnCfginfo.getStatus());
            bTxnLimitCfgMC.setAuditStatus(txnCfginfo.getAuditStatus());
            bTxnLimitCfgMC.setOprId(txnCfginfo.getOprId());
            bTxnLimitCfgMC.setCrtOrgId(txnCfginfo.getCrtOrgId());
            bTxnLimitCfgMC.setCreateTime(txnCfginfo.getCreateTime());
            bTxnLimitCfgMC.setId( txnCfginfo.getNotDiffAcctId());
            merchantBaseInfoMapper.insert(bTxnLimitCfgMC);


            //借记限额
            BTxnLimitCfg bTxnLimitCfgLoa=new BTxnLimitCfg();
            bTxnLimitCfgLoa.setInstId(instId);
            bTxnLimitCfgLoa.setLimitType( txnCfginfo.getLimitType());
            bTxnLimitCfgLoa.setLimitInst( txnCfginfo.getMcNo() + "|" + txnCfginfo.getMcTermNo());
            bTxnLimitCfgLoa.setLimitAcctType("20");//20-借记账户(包括本行、他行借记账户)  21-贷记账户(包括本行、他行贷记账户)


            bTxnLimitCfgLoa.setSingleLimitMaxAmt(txnCfginfo.getSingleLimitLoanMaxAmt());
            bTxnLimitCfgLoa.setDayLimitAmt( txnCfginfo.getDayLimitLoanAmt());
            bTxnLimitCfgLoa.setMonthLimitAmt( txnCfginfo.getMonthLimitLoanAmt());

            bTxnLimitCfgLoa.setStatus( txnCfginfo.getStatus());
            bTxnLimitCfgLoa.setAuditStatus( txnCfginfo.getAuditStatus());
            bTxnLimitCfgLoa.setOprId( txnCfginfo.getOprId());
            bTxnLimitCfgLoa.setCrtOrgId( txnCfginfo.getCrtOrgId());
            bTxnLimitCfgLoa.setCreateTime( txnCfginfo.getCreateTime());
            bTxnLimitCfgLoa.setId( txnCfginfo.getLoanId());
            merchantBaseInfoMapper.insert(bTxnLimitCfgLoa);
            //贷记限额

            BTxnLimitCfg bTxnLimitCfgCre=new BTxnLimitCfg();
            bTxnLimitCfgCre.setInstId(instId);
            bTxnLimitCfgCre.setLimitType( txnCfginfo.getLimitType());
            bTxnLimitCfgCre.setLimitInst( txnCfginfo.getMcNo() + "|" + txnCfginfo.getMcTermNo());
            bTxnLimitCfgCre.setLimitAcctType("21");//20-借记账户(包括本行、他行借记账户)  21-贷记账户(包括本行、他行贷记账户)


            bTxnLimitCfgCre.setSingleLimitMaxAmt(txnCfginfo.getSingleLimitCreditMaxAmt());
            bTxnLimitCfgCre.setDayLimitAmt( txnCfginfo.getDayLimitCreditAmt());
            bTxnLimitCfgCre.setMonthLimitAmt( txnCfginfo.getMonthLimitCreditAmt());

            bTxnLimitCfgCre.setStatus( txnCfginfo.getStatus());
            bTxnLimitCfgCre.setAuditStatus( txnCfginfo.getAuditStatus());
            bTxnLimitCfgCre.setOprId( txnCfginfo.getOprId());
            bTxnLimitCfgCre.setCrtOrgId( txnCfginfo.getCrtOrgId());
            bTxnLimitCfgCre.setCreateTime( txnCfginfo.getCreateTime());
            bTxnLimitCfgCre.setId( txnCfginfo.getCreditId());
            merchantBaseInfoMapper.insert(bTxnLimitCfgCre);
        } catch (Exception e) {
            // TODO: handle exception
            log.error("交易出现异常，异常信息：" + e.getMessage());
            throw new RedpException("交易出现异常，异常信息：" + e.getMessage());
        }

    }
    @Transactional(value = "transactionManager")
    public void editMcQuota(BTxnLimitCfg txnCfginfo) throws RedpException {
        try {
            BTxnLimitCfg oldData=new BTxnLimitCfg();
            if ("11".equals(txnCfginfo.getLimitType())) {
                oldData = getMcQuotaDetail(txnCfginfo);

            } else if ("12".equals(txnCfginfo.getLimitType())) {
                //获取终端限额数据
                oldData=getTermQuotaById(txnCfginfo);
            } else {
                throw new RedpException("限额信息参数有误");
            }
            txnCfginfo.setOprId(oldData.getOprId());
            txnCfginfo.setCreateTime(oldData.getCreateTime());
            UpmpUserInfoVO user = RedpUpmpUtil.getCurrentUser(txnCfginfo.getInstId());
            UpmpPrivilegeCheck privilegeCheckByPrivilegeCode = authPrivilegeCheckService.getPrivilegeCheckByPrivilegeCode(txnCfginfo.getInstId(), "merchantLevelManager:edit");

            if (null == privilegeCheckByPrivilegeCode) {
                throw new RedpException("获取审核信息失败");
            }
            boolean checked = BusinessContainer.YES.equals(privilegeCheckByPrivilegeCode.getChecked());
            if (checked) {
                //修改正式表
                txnCfginfo.setLimitType("11"); //11-商户限额
                txnCfginfo.setStatus(oldData.getStatus());
                txnCfginfo.setBizStatus(BizDataStatusEnum.STATUS_DRAFT.getType());
                txnCfginfo.setAuditStatus(BizDataAuditStatusEnum.AUDIT_STATUS_UPD_CHECKING.getType());
                txnCfginfo.setLastOprId(user.getOprId());
                txnCfginfo.setLastUpdateTime(DateUtils.formatDate(new Date(), DateUtils.DEFAULT_TIME_FORMAT));
                editMerchantQutaAuthStatus(txnCfginfo);
                //修改临时表
                saveBizTmp(txnCfginfo, BizOprEnum.OPR_UPDATE.getType());

            } else if (!checked) {
                txnCfginfo.setLimitType("11"); //11-商户限额
                txnCfginfo.setStatus("Y");
                txnCfginfo.setBizStatus(BizDataStatusEnum.STATUS_NORMAL.getType());
                txnCfginfo.setAuditStatus(BizDataAuditStatusEnum.AUDIT_STATUS_UPD_PASS.getType());
                txnCfginfo.setLastOprId(user.getOprId());
                txnCfginfo.setLastUpdateTime(DateUtils.formatDate(new Date(), DateUtils.DEFAULT_TIME_FORMAT));
                editMerchantQutaInfo(txnCfginfo);
                //保存历史表
                saveQuotaBizHis(txnCfginfo,oldData, BizOprEnum.OPR_UPDATE.getType());
            }
        } catch (Exception e) {
            log.error("修改商户限额配置时系统异常:[{}]", e);
            throw new RedpException("修改商户限额配置时系统异常");
        }
    }
    //启用
    @Transactional(value = "transactionManager")
    public void startMcLevelQuota(HttpServletRequest request,BTxnLimitCfg req) throws RedpException {
        String limitType = request.getParameter("limitType");
        BTxnLimitCfg txnCfginfo = null;
        if ("11".equals(limitType)) {
            txnCfginfo = getMcQuotaDetail(req);
        } else if ("12".equals(limitType)) {
            txnCfginfo = getTermQuotaById(req);
        } else {
            throw new RedpException("限额类型不匹配");
        }
        txnCfginfo.setInstId(req.getInstId());
        BTxnLimitCfg oldData = new BTxnLimitCfg();
        BeanUtils.copyProperties(txnCfginfo,oldData);

        UpmpUserInfoVO user = RedpUpmpUtil.getCurrentUser(req.getInstId());
        UpmpOrganization org = upmpOrganizationService.getOrgByCode(user.getOrgCode(), user.getInstId());
        UpmpPrivilegeCheck privilegeCheckByPrivilegeCode = authPrivilegeCheckService.getPrivilegeCheckByPrivilegeCode(txnCfginfo.getInstId(), "merchantLevelManager:use");

        if (null == privilegeCheckByPrivilegeCode) {
            throw new RedpException("获取审核信息失败");
        }

        boolean checked = BusinessContainer.YES.equals(privilegeCheckByPrivilegeCode.getChecked());
        if (checked) {
            //     txnCfginfo.setStatus("N"); //Y 启用 N停用
            //     txnCfginfo.setBizStatus(BizDataStatusEnum.STATUS_DRAFT.getType());
            txnCfginfo.setAuditStatus(BizDataAuditStatusEnum.AUDIT_STATUS_USE_CHECKING.getType());
            txnCfginfo.setLastOprId(user.getOprId());
            txnCfginfo.setLastUpdateTime(DateUtils.formatDate(new Date(), DateUtils.DEFAULT_TIME_FORMAT));

            //修正式表
            editMerchantQutaAuthStatus(txnCfginfo);
            //修改临时表
            saveBizTmp(txnCfginfo, BizOprEnum.OPR_USE.getType());
        } else {
            txnCfginfo.setStatus("Y"); //Y 启用 N停用
            txnCfginfo.setBizStatus(BizDataStatusEnum.STATUS_NORMAL.getType());
            txnCfginfo.setAuditStatus(BizDataAuditStatusEnum.AUDIT_STATUS_USE_PASS.getType());
            txnCfginfo.setOprId(user.getOprId());
            txnCfginfo.setCreateTime(DateUtils.formatDate(new Date(), DateUtils.DEFAULT_TIME_FORMAT));
            //保存正式表
            editMerchantQutaInfo(txnCfginfo);
            //保存历史表
            saveQuotaBizHis(txnCfginfo,oldData, BizOprEnum.OPR_USE.getType());
        }
    }

//注销
    @Transactional(value = "transactionManager")
    public void deleteMcLevelQuota(HttpServletRequest request,BTxnLimitCfg req) throws RedpException {
        String limitType = request.getParameter("limitType");
        BTxnLimitCfg txnCfginfo = null;
        if ("11".equals(limitType)) {
            txnCfginfo = getMcQuotaDetail(req);
        } else if ("12".equals(limitType)) {
            txnCfginfo = getTermQuotaById(req);
        } else {
            throw new RedpException("限额类型不匹配");
        }
        BTxnLimitCfg oldData = new BTxnLimitCfg();
        txnCfginfo.setInstId(req.getInstId());
        BeanUtils.copyProperties(txnCfginfo,oldData);
        UpmpUserInfoVO user = RedpUpmpUtil.getCurrentUser(req.getInstId());
        UpmpOrganization org = upmpOrganizationService.getOrgByCode(user.getOrgCode(), user.getInstId());
        UpmpPrivilegeCheck privilegeCheckByPrivilegeCode = authPrivilegeCheckService.getPrivilegeCheckByPrivilegeCode(req.getInstId(), "merchantLevelManager:cancel");

     if (null == privilegeCheckByPrivilegeCode) {
            throw new RedpException("获取审核信息失败");
        }

        boolean checked = BusinessContainer.YES.equals(privilegeCheckByPrivilegeCode.getChecked());
        if (checked) {

            //      txnCfginfo.setBizStatus(BizDataStatusEnum.STATUS_DRAFT.getType());
            txnCfginfo.setAuditStatus(BizDataAuditStatusEnum.AUDIT_STATUS_CANCEL_CHECKING.getType());
            txnCfginfo.setLastOprId(user.getOrgId());
            txnCfginfo.setLastUpdateTime(DateUtils.formatDate(new Date(), DateUtils.DEFAULT_TIME_FORMAT));

            //修正式表
            editMerchantQutaAuthStatus(txnCfginfo);
            //修改临时表
            saveBizTmp(txnCfginfo, BizOprEnum.OPR_CANCEL.getType());
        } else {
            txnCfginfo.setStatus("N");
            txnCfginfo.setBizStatus(BizDataStatusEnum.STATUS_CANCELED.getType());
            txnCfginfo.setAuditStatus(BizDataAuditStatusEnum.AUDIT_STATUS_CANCEL_PASS.getType());
            txnCfginfo.setOprId(user.getOprId());
            txnCfginfo.setCreateTime(DateUtils.formatDate(new Date(), DateUtils.DEFAULT_TIME_FORMAT));
            //保存正式表
            editMerchantQutaInfo(txnCfginfo);
            //保存历史表
            saveQuotaBizHis(txnCfginfo,oldData, BizOprEnum.OPR_CANCEL.getType());
        }
    }
    /**
     * 获取终端限额信息List
     */
    public Page<BTxnLimitCfg> getTermQuotaList(String mcNo, BTxnLimitCfg request) throws RedpException {
        try {
            UpmpUserInfoVO user = RedpUpmpUtil.getCurrentUser(request.getInstId());
            List<BTxnLimitCfg> resultListCount= merchantBaseInfoMapper.getTermQuotaList(request.getInstId(),  mcNo + "|%");
            return new PageImpl<BTxnLimitCfg>(resultListCount);
        } catch (Exception e) {
            // TODO: handle exception
            log.error("交易出现异常，异常信息：" + e.getMessage());
            throw new RedpException("交易出现异常，异常信息：" + e.getMessage());
        }
    }
    /**
     * 新增页面 获取  未配置的商户号
     */
    public List<BTxnLimitCfg> getNotAddMCInfo(String instId) throws RedpException {
        try {
            List<BTxnLimitCfg> resultList = merchantBaseInfoMapper.getNotAddMCInfo(instId);

            return resultList;
        } catch (Exception e) {
            // TODO: handle exception
            log.error("交易出现异常，异常信息：" + e.getMessage());
            throw new RedpException("交易出现异常，异常信息：" + e.getMessage());
        }
    }

    @Transactional(value = "transactionManager")
    public void batchUploadBankQuotal(ArrayList<BTxnLimitCfg> bankLevelQuotaList,String instId) throws RedpException {

        UpmpPrivilegeCheck privilegeCheckByPrivilegeCode = authPrivilegeCheckService.getPrivilegeCheckByPrivilegeCode(instId, "merchantLevelManager:import");

        if (null == privilegeCheckByPrivilegeCode) {
            throw new RedpException("获取审核信息失败");
        }

        boolean checked = BusinessContainer.YES.equals(privilegeCheckByPrivilegeCode.getChecked());
        if (checked) {
            bankLevelQuotaList.forEach((e) -> {
                try {
                    uploadIsChecked(e);
                } catch (RedpException ex) {
                    throw new RuntimeException(ex);
                }
            });
        } else {

            bankLevelQuotaList.forEach((e) -> {
                try {
                    uploadNotChecked(e);
                } catch (RedpException ex) {
                    throw new RuntimeException(ex);
                }
            });
        }
    }

    private void uploadIsChecked(BTxnLimitCfg txnCfginfo) throws RedpException {
        UpmpUserInfoVO user = RedpUpmpUtil.getCurrentUser(txnCfginfo.getInstId());
        String industryType = txnCfginfo.getIndustryType();
        txnCfginfo.setLimitType("11");
        txnCfginfo.setLimitInst(txnCfginfo.getMcNo());
        //设置数据Id
        txnCfginfo.setNotDiffAcctId(CommonUtils.getUUID());
        txnCfginfo.setCreditId(CommonUtils.getUUID());
        txnCfginfo.setLoanId(CommonUtils.getUUID());
        txnCfginfo.setRefundNotDiffAcctId(CommonUtils.getUUID());
        txnCfginfo.setRefundLoanId(CommonUtils.getUUID());
        txnCfginfo.setRefundCreditId(CommonUtils.getUUID());

        //    txnCfginfo.setInstId(user.getInstId());

        txnCfginfo.setStatus("N"); //Y 启用 N停用
        txnCfginfo.setBizStatus(BizDataStatusEnum.STATUS_DRAFT.getType());
        txnCfginfo.setAuditStatus(BizDataAuditStatusEnum.AUDIT_STATUS_ADD_CHECKING.getType());
        txnCfginfo.setOprId(user.getOprId());
        txnCfginfo.setCreateTime(DateUtils.formatDate(new Date(), DateUtils.DEFAULT_TIME_FORMAT));
        //保存正式表
        saveMerchantQutaInfo(txnCfginfo);
        //保存零时表
        saveBizTmp(txnCfginfo, BizOprEnum.OPR_ADD.getType());

    }

    private void uploadNotChecked(BTxnLimitCfg txnCfginfo) throws RedpException {
        UpmpUserInfoVO user = RedpUpmpUtil.getCurrentUser(txnCfginfo.getInstId());
        String industryType = txnCfginfo.getIndustryType();
        txnCfginfo.setLimitType("11");
        txnCfginfo.setLimitInst(txnCfginfo.getMcNo());


        //设置数据Id
        txnCfginfo.setNotDiffAcctId(CommonUtils.getUUID());
        txnCfginfo.setCreditId(CommonUtils.getUUID());
        txnCfginfo.setLoanId(CommonUtils.getUUID());
        txnCfginfo.setRefundNotDiffAcctId(CommonUtils.getUUID());
        txnCfginfo.setRefundLoanId(CommonUtils.getUUID());
        txnCfginfo.setRefundCreditId(CommonUtils.getUUID());
        //  txnCfginfo.setInstId(user.getInstId());

        txnCfginfo.setStatus("Y"); //Y 启用 N停用
        txnCfginfo.setBizStatus(BizDataStatusEnum.STATUS_NORMAL.getType());
        txnCfginfo.setAuditStatus(BizDataAuditStatusEnum.AUDIT_STATUS_ADD_PASS.getType());
        txnCfginfo.setOprId(user.getOprId());
        txnCfginfo.setCreateTime(DateUtils.formatDate(new Date(), DateUtils.DEFAULT_TIME_FORMAT));
        //保存正式表
        saveMerchantQutaInfo(txnCfginfo);
        //保存历史表

        saveQuotaBizHis(txnCfginfo,null, BizOprEnum.OPR_ADD.getType());
    }

    /**
     * 获取新增页终端编号数据
     *
     * @param mcNo
     * @return
     */
    public List<BTxnLimitCfg> getAddTermNoList(String mcNo, String instId,String opp) throws RedpException {
        try {
            List<BTxnLimitCfg> mcQuotaDetail = new ArrayList<>();

            List<BTxnLimitCfg> resultList = merchantBaseInfoMapper.getAddTermNoList(mcNo + "|%", instId, mcNo,opp);

            if (resultList.size() > 0) {
                return resultList;
            } else {
                return mcQuotaDetail;
            }
        } catch (Exception e) {
            // TODO: handle exception
            log.error("交易出现异常，异常信息：" + e.getMessage());
            throw new RedpException("交易出现异常，异常信息：" + e.getMessage());
        }
    }

    private List<TermInfoBean> mapTermInfoList(List resultList) {
        ArrayList<TermInfoBean> termList = new ArrayList<>();
        resultList.forEach((e) -> {
            TermInfoBean termInfo = new TermInfoBean();
            Map emap = (Map) e;
            termInfo.setTermNo((String) emap.get("TERM_NO"));
            termInfo.setTermSn((String) emap.get("TM_NAME"));
            termList.add(termInfo);
        });
        return termList;
    }

    @Override
    public boolean saveBatch(Collection<BTxnLimitCfg> entityList, int batchSize) {
        return false;
    }

    @Override
    public boolean saveOrUpdateBatch(Collection<BTxnLimitCfg> entityList, int batchSize) {
        return false;
    }

    @Override
    public boolean updateBatchById(Collection<BTxnLimitCfg> entityList, int batchSize) {
        return false;
    }

    @Override
    public boolean saveOrUpdate(BTxnLimitCfg entity) {
        return false;
    }

    @Override
    public BTxnLimitCfg getOne(Wrapper<BTxnLimitCfg> queryWrapper, boolean throwEx) {
        return null;
    }

    @Override
    public Map<String, Object> getMap(Wrapper<BTxnLimitCfg> queryWrapper) {
        return null;
    }

    @Override
    public <V> V getObj(Wrapper<BTxnLimitCfg> queryWrapper, Function<? super Object, V> mapper) {
        return null;
    }

    @Override
    public BaseMapper<BTxnLimitCfg> getBaseMapper() {
        return null;
    }
}
